var app = getApp();
var iv=null;
var encryptedData=null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loginInfo: {},
    jie:false,
    is_reset_apply:false
  },
  // 打开重置申请
  open_reset_apply:function(){
    this.setData({
      is_reset_apply:true
    });
  },
  // 关闭重置申请
  reset_cancel:function(){
    this.setData({
      is_reset_apply:false
    });
  },
  // 拒绝与取消申请
  toabout: function () {
    var that = this;
    //*注意邀请页this.data.loginInfo是发送者的基本信息
    //app.globalData.loginInfo是当前使用者的基本信息
    if(app.globalData.loginInfo.is_manage==2){  //我是管理员
      app.AppHttp('api/Client/agreeOrRejectBind', {
        openid: app.globalData.openid
      }, function (res) {
        if (res.data.status == 1) {
          wx.showToast({
            title: res.data.msg,
            mask:true,
            success: function () {  
              app.globalData.list=[];
              that.setData({
                is_reset_apply:false,
                jie:false,
                yiruzhu:2
              });
              that.statusShow();
            }
          });
        }
      });
    }else if(app.globalData.loginInfo.is_manage==1){  //我是员工
      app.AppHttp('api/Client/refuseInvite', {
        openid: app.globalData.openid
      }, function (res) {
        if (res.data.status == 1) {
          wx.showToast({
            title: res.data.msg,
            mask:true,
            success: function () {  
              app.globalData.list=[];
              that.setData({
                is_reset_apply:false,
                jie:false,
                yiruzhu:2
              });
              that.statusShow();
            }
          });
        }
      })
    }
  },
  // 点击接受
  jieshou:function(){
    var that = this;
    app.AppHttp('api/Client/acceptInvite', {
      ShareOpenid: app.globalData.ShareOpenid,
      openid: app.globalData.openid,
      part_id:app.globalData.part_id
    }, function(res) {
      console.log(res)
      if (res.data.status == 1) {
        that.setData({
          jie:true,
          client_id:that.data.loginInfo.id,
          yiruzhu:2
        });    
      } else {
        wx.showToast({
          title: '接受失败',
        })
      }
    });
  },
  goshangpin:function(){
    wx.switchTab({
      url: '../../shangpin/shangpin'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   * 说明:jie == true   等待审核  == false 接受/拒绝
   *      yiruzhu == 1  已入驻   2：未入驻
   */
  statusShow: function () {
    var that = this;
    wx.showLoading({
      title:'加载中...'
    });
    wx.request({
      url: 'https://www.xiaobangcai.com/get_appid_secret/xd',
      method: 'GET',
      data: {},
      success: function(res) {
        console.log(JSON.stringify(res.data));
        app.globalData.appId=res.data.appId;
        app.globalData.secret=res.data.secret;
        wx.login({
          success: function (res) {
            wx.request({
              url: app.globalData.url + "api/Client/getClientOpenId",
              method: 'POST',
              data: {
                appId: app.globalData.appId,
                secret: app.globalData.secret,
                code: res.code
              },
              success: function (res) {
                var jie;
                var yiruzhu;
                var step;
                app.globalData.openid = res.data.openid;
                app.globalData.unionid = res.data.unionid;
                wx.request({
                  url: app.globalData.url + "api/Client/personalBasic",
                  method: 'POST',
                  data: {
                    openid: res.data.openid
                  },
                  success: function (res) {
                    console.log(JSON.stringify(res.data));
                    var data = res.data;
                    app.globalData.person_id = data.data.id;  //用户个人id
                    if (data.status == 1) {
                      if (data.data.client_id > 0 && data.data.is_validate == 1) {//有门店&申请通过
                        step=3;
                        yiruzhu = 1;
                        wx.request({
                          url: app.globalData.url + 'api/Client/basicInfo',
                          method: "POST",
                          data: {
                            openid: app.globalData.openid
                          },
                          success: function (res) {
                            app.globalData.loginInfo = res.data;  //受邀者信息
                            that.setData({
                              myclient: res.data.client_abbre
                            });
                            console.log(that.data.myclient);
                          }
                        })
                      } else if (data.data.client_id == 0 && data.data.is_validate == 0) {  //未申请门店
                        yiruzhu = 2;
                        jie = false;
                        if (res.data.data.phone.length != 11) {  // 未注册手机号
                          step=1;                     
                        }else if (res.data.data.phone.length ==11) {  // 还没有门店          
                          step=2;
                        };       
                      } else if (data.data.client_id > 0 && data.data.is_validate == 0) { //已申请，但还未通过
                        yiruzhu = 2;
                        jie = true;
                        if (res.data.data.phone.length != 11) {   // 未注册手机号
                          step=1;                 
                        }else if (res.data.data.phone.length ==11) {  // 还没有门店                    
                          step=2;
                        };
                      }
                    }else {
                      step=0;
                      yiruzhu = 2;
                      jie = false;
                    };
                    console.log(step);
                    app.globalData.step=step;
                    that.setData({
                      client_id:data.data.client_id,
                      step:step,
                      ShareOpenid: app.globalData.ShareOpenid,
                      type: that.data.type,
                      jie: jie,
                      yiruzhu: yiruzhu
                    });
                    wx.hideLoading();
                  }
                })
              }
            })
          }
        })
      }
    });
  },
  onLoad(options) {
    var that = this;
    //得到参数
    app.globalData.ShareOpenid = options.ShareOpenid;
    app.globalData.type = options.type;
    app.globalData.part_id = options.part_id;  //是否直接邀请进组
    //1：如果有门店，如果当前人状态是0，就显示，取消申请，状态为1，直接可以进入软件
    //2:如果没有门店，(1):显示拒绝|接受 (2)点击接受之后   -------------------> 1
    wx.request({
      url: app.globalData.url + 'api/Client/basicInfo',
      method: "POST",
      data: {
        openid: app.globalData.ShareOpenid
      },
      success: function (res) {
        console.log(JSON.stringify(res.data));
        that.setData({
          loginInfo: res.data  //发出者信息
        });
      }
    })
  },
  // 点击刷新，查看申请状态
  shuaxin: function () {
    this.statusShow();
  },
  // 微信授权
  getUserProfile:function(e){
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        var userInfo=res.userInfo;
        var that = this;
        wx.login({
          success: function (ress) {
            console.log(userInfo);
            var data = {
              appId: app.globalData.appId,
              secret: app.globalData.secret,
              code: ress.code,
              head_portrait: userInfo.avatarUrl,
              avatarUrl: userInfo.avatarUrl,
              sex: userInfo.gender,
              country: userInfo.country,
              nickname: userInfo.nickName,
              dk_type:0,
            };
            app.AppHttp('api/Client/ClientPersonalAuth', data, function (res) {
              if (res.data.status == 1) {
                wx.showToast({
                  title: res.data.msg,
                  success: function () {
                    app.globalData.step=1;
                    that.setData({
                      step:1
                    });
                    setTimeout(function () {
                      if(app.globalData.unionid==undefined){ 
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                        wx.getUserInfo({
                          success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            console.log(res);
                            encryptedData=res.encryptedData;
                            iv=res.iv;
                            app.globalData.userInfo = res.userInfo
                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            var sdata = {
                              appId: app.globalData.appId,
                              sessionKey:app.globalData.session_key,
                              encryptedData:encryptedData,
                              iv:iv
                            };
                            app.AppHttp('api/Client/DataDecryption',sdata, function (res) {
                              console.log(JSON.stringify(res.data));
                                app.globalData.unionid = res.data.unionId;
                                app.AppHttp('api/Client/updateUnionid',{openid:app.globalData.openid,unionid:res.data.unionId}, function (res) {
                                  console.log(JSON.stringify(res.data));  
                                });           
                            });
                          }
                        });            
                      };
                    })
                  }
                }, 2000);
              } else {
                wx.showModal({
                  title: '授权异常'
                })
              }
            });
          }
        });
      }
    })
  },
   // 获取手机号
   getPhoneNumber:function(e){
    var that = this;
    if(e.detail.errMsg == "getPhoneNumber:ok"){  //用户点击了允许
      var iscj=e.currentTarget.dataset.iscj;
      wx.login({
        success:function(res){
          var data = {
            appId: app.globalData.appId,
            sessionKey:app.globalData.session_key,
            encryptedData:e.detail.encryptedData,
            iv:e.detail.iv
          };
          app.AppHttp('api/Client/DataDecryption',data, function (res) {
            console.log(JSON.stringify(res.data));
            if(app.globalData.unionid==undefined){   //没有unionId，更新unionId
              app.globalData.unionid = res.data.unionId;
              console.log(res.data.phoneNumber);
              app.AppHttp('api/Client/updateUnionid',{openid:app.globalData.openid,unionid:res.data.unionId}, function (res) {
                console.log(JSON.stringify(res.data));  
              });
            };
            that.bind_and_cre(res.data.phoneNumber,'join');            
          });
        }
      })
    }else{
      console.log('已经拒绝');
    };
  },
  // 仅绑定手机
  bind_and_cre:function(phone,join_type){
    var that = this;
    app.AppHttp('api/Client/WechatUserBindSupplier',{openid:app.globalData.openid,phone:phone,join_type:join_type}, function (res) {
      console.log(JSON.stringify(res.data));
      wx.showToast({
        title: res.data.msg
      }); 
      app.globalData.step=2;  
      that.setData({
        step:2
      });
      that.jieshou();    
    });
  },
  // 去注销或解绑
  to_unbind_cancell:function(){
    if(app.globalData.loginInfo.porgram_employee_id>0 && app.globalData.loginInfo.is_manage==2){
      wx.showModal({
        title: '提示',
        content:'您属于企业下的档口客户\n没有主动注销的权限\n请联系企业管理员，解除合作关系',
        showCancel: false,
        confirmText:"我知道了",
        success: function (res) {}
      });
      return;
    };
    wx.navigateTo({
      url:'/pages/wo/gerenshezhi/gerenshezhi?is_auto='+1
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    this.statusShow();
    app.globalData.test = 0; //退出体验账号
    wx.hideHomeButton();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.statusShow();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})